package dao

import (
	"context"
	"coolcar/v1/blob/api/gen/v1"
	"coolcar/v1/shared/ids"
	"coolcar/v1/shared/mgutils"
	"coolcar/v1/shared/mgutils/objid"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

// Mongo defines a blob mongo client.
type Mongo struct {
	col *mongo.Collection
}

// NewMongo creates a new blob Mongo dao.
func NewMongo(db *mongo.Database) *Mongo {
	return &Mongo{
		col: db.Collection("blob"),
	}
}

type BlobRecord struct {
	mgutils.IDField `bson:"inline"`
	Aid             ids.AccountID `bson:"accountid"`
	Path            string        `bson:"path"`
}

func (m *Mongo) CreateBlob(ctx context.Context, aid ids.AccountID) (*BlobRecord, error) {
	br := &BlobRecord{
		Aid: aid,
	}
	objID := mgutils.NewObjID()
	br.ID = objID
	br.Path = fmt.Sprintf("%s/%s", aid.String(), objID.Hex())
	_, err := m.col.InsertOne(ctx, br)
	if err != nil {
		return nil, err
	}
	return br, nil
}

func (m *Mongo) GetBlob(ctx context.Context, bid ids.BlobID) (*BlobRecord, error) {
	filter := bson.M{
		mgutils.IDFieldName: objid.MustFromID(bid),
	}
	res := m.col.FindOne(ctx, filter)
	if err := res.Err(); err != nil {
		return nil, err
	}
	var br BlobRecord
	err := res.Decode(&br)
	if err != nil {
		return nil, fmt.Errorf("failed to decode blob: %v", err)
	}
	return &br, nil
}

func (m *Mongo) GetBlobURL(ctx context.Context, request *blobpb.GetBlobURLRequest) (*blobpb.GetBlobURLResponse, error) {
	//TODO implement me
	panic("implement me")
}
